package com.github.catvod.spider;

import android.text.TextUtils;

import com.github.catvod.bean.Class;
import com.github.catvod.bean.Result;
import com.github.catvod.bean.Vod;
import com.github.catvod.bean.ali.Code;
import com.github.catvod.crawler.Spider;

import com.github.catvod.net.OkHttp;
import com.github.catvod.net.OkResult;

import com.github.catvod.utils.ChaoJiYing;
import com.github.catvod.utils.DadaguiUtil;
import com.github.catvod.utils.Notify;
import com.github.catvod.utils.OCR;
import com.github.catvod.utils.Util;

import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 达达龟发布页: https://www.dadagui.vip
 */
public class DadaGui extends Spider {

    private String siteUrl="https://www.dadagui.la/";
    private String searchUrl=siteUrl+"vodsearch/-------------.html";
    private String API_URL=siteUrl+"webcloud/api.php";
    private String verifyImgUrl=siteUrl+"index.php/verify/index.html?";
    private String verifyUrl=siteUrl+"index.php/ajax/verify_check";

    private static String commo_Cookies="33fekod3e25nhevff3hti4v4uk";
    private Map<String, String> getHeader() {
        Map<String, String> header = new HashMap<>();
        header.put("user-Agent",Util.CHROME);
        header.put("cookie", "erdangjiade=erdangjiade; PHPSESSID="+commo_Cookies);
        return header;
    }

    private Map<String, String> getSearchHeader(String cookies) {
        Map<String, String> header = new HashMap<>();
        header.put("user-Agent",Util.CHROME);
        header.put("cookie", "erdangjiade=erdangjiade; PHPSESSID="+cookies);
        return header;
    }

    @Override
    public String homeContent(boolean filter) throws Exception {
        List<Class> classes= new ArrayList<>();
        List<String> typeIds = Arrays.asList("/", "1", "2", "3", "4");
        List<String> typeNames = Arrays.asList("首页", "电影", "剧集", "综艺", "动漫");
        for (int i = 0; i < typeIds.size(); i++) {
            classes.add(new Class(typeIds.get(i), typeNames.get(i)));
        }
        // 进行获取推荐
        Document doc = Jsoup.parse(OkHttp.string(siteUrl, getHeader()));
        List<Vod> list=parseVoc(doc);
        return Result.string(classes, list);
    }

    /**
     * 分类
     * @param tid
     * @param pg
     * @param filter
     * @param extend
     * @return
     * @throws Exception
     */
    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) throws Exception {
        // 进行判断是否是首页
        String categoryUrl;
        if(tid.endsWith("/")){
            // 进行获取首页全
            categoryUrl=siteUrl;
        }else {
            categoryUrl=siteUrl+"vodtype/"+tid+"-"+pg+".html";
        }
        Document doc = Jsoup.parse(OkHttp.string(categoryUrl, getHeader()));
        List<Vod> videos=parseVoc(doc);
        // 总页数
        Integer total = (Integer.parseInt(pg) + 1) * 30;
        return Result.string(Integer.parseInt(pg), Integer.parseInt(pg)+1,videos.size(),total,videos);
    }


    /**
     * 播放详情
     * @param ids
     * @return
     * @throws Exception
     */
    @Override
    public String detailContent(List<String> ids) throws Exception {
        String vodId = ids.get(0);
        // 进行去除域名最后的/
        if (siteUrl.endsWith("/")){
            siteUrl=siteUrl.substring(0, siteUrl.length() - 1);
        }
        Document doc = Jsoup.parse(OkHttp.string(siteUrl + vodId, getHeader()));
        String title = doc.select("h1.title").text();
        String pic = doc.select("a.pic > img").attr("data-original");
        // 描述
        String description = doc.select("span.detail-content").text();
        String content= doc.select("p.data.visible-xs").text();
        // 进行获取播放链路名称
        String playerFrom = doc.select("div.stui-vodlist__head > h3").text();
        // 空格进行切割,并去除最后一个
        String[] playerFromList = playerFrom.substring(0, playerFrom.length() - 1).split(" ");
        // 进行去除最后一个元素
        playerFromList = Arrays.copyOfRange(playerFromList, 0, playerFromList.length - 1);
        // 进行获取播放剧集
        Elements ul_list = doc.select("ul.stui-content__playlist.clearfix");
        StringBuilder playerUrl= new StringBuilder();
        for (Element ul : ul_list) {
            Elements a_list = ul.select("li > a");
            for (Element a : a_list) {
                String href = a.attr("href");
                String name = a.text();
                // 进行判断如果是最后一个元素不加#号
                if (a_list.get(a_list.size() - 1).equals(a)){
                    playerUrl.append(name).append("$").append(href);
                }else {
                    playerUrl.append(name).append("$").append(href).append("#");
                }
            }
            playerUrl.append("$$$");
        }
        System.out.println(Arrays.toString(playerFromList));
        System.out.println(playerUrl);
        Vod vod = new Vod();
        vod.setVodId(vodId);
        vod.setVodPic(pic);
        vod.setVodName(title);
        vod.setVodRemarks(content);
        vod.setVodPlayFrom(TextUtils.join("$$$", playerFromList));
        vod.setVodPlayUrl(playerUrl.toString());
        vod.setVodContent(description);
       return Result.string(vod);
    }

    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) throws Exception {
        if (siteUrl.endsWith("/")){
            siteUrl=siteUrl.substring(0, siteUrl.length() - 1);
        }
        // 进行获取播放url
        String html = OkHttp.string(siteUrl + id);
        // 进行匹配var player_aaaa
        Pattern pattern = Pattern.compile("var player_aaaa=(.*)");
        Matcher matcher = pattern.matcher(html);
        String playerJson = matcher.find() ? matcher.group(1) : "";
        System.out.println(playerJson);
        JSONObject jsonObject = new JSONObject(playerJson);
        // 进行获取url=播放请求的加密vid
        String vid = jsonObject.getString("url");
        // 进行请求播放api
        Map<String, String> params = new HashMap<>();
        params.put("vid", vid);
        OkResult post = OkHttp.post(API_URL, params, getHeader());
        String body = post.getBody();
        JSONObject bodyJson = new JSONObject(body);
        // 进行获取播放url
        String encorytUrl = bodyJson.getJSONObject("data").getString("url");
        // 进行解密获取url
        String url = DadaguiUtil.getPlayUrl(encorytUrl);
        return Result.get().url(url).parse().header(getHeader()).string();
    }

    @Override
    public String searchContent(String key, boolean quick) throws Exception {
        HashMap<String, String> params = new HashMap<>();
        params.put("wd", key);
        params.put("submit", "");
        OkResult post = OkHttp.post(searchUrl, params,getHeader());
        String body = post.getBody();
        Document doc = Jsoup.parse(body);
        if (!doc.select(".msg_jump_tit").isEmpty()){
            System.out.println("达达猫搜索失败啦");
            // 自动进行设置更新自动进行获取cookie
            Map<String, List<String>> resp = post.getResp();
            String cookies = "";
            if (resp.containsKey("Set-Cookie")){
                Pattern pattern = Pattern.compile("PHPSESSID=(.*);");
                Matcher matcher = pattern.matcher(Objects.requireNonNull(resp.get("Set-Cookie")).get(0));
                cookies = matcher.find() ? matcher.group(1) : "";
            }else{
                cookies = commo_Cookies;
            }
            // 进行验证过验证码
            HashMap<String, String> verify_params = new HashMap<>();
            verify_params.put("type", "search");
            // 进行请求获取图片的二进制流数据
            byte[] imgUrlByte = Util.getImgUrlByte(verifyImgUrl, cookies);
            JSONObject ocr_result = new JSONObject(ChaoJiYing.PostPic("fushong", "17341907254fu", "967461", "4004", "4", imgUrlByte));
            // 进行获取识别结果
            String pic_result = ocr_result.getString("pic_str");
            // 进行获取识别图片的id
            String pic_id = ocr_result.getString("pic_id");
            System.out.println(cookies);
            // 进行判断验证码是否正确
            try {
                JSONObject verify_result = new JSONObject(pass_verification_code(pic_result,cookies));
                String verify_code = new JSONObject(verify_result.toString()).getString("code");
                if (verify_code.equals("1002")){
                    Notify.show("枫斗~达达猫自动过验证码失败!");
                    // 报告验证失败
                    String err_result = ChaoJiYing.ReportError("fushong", "17341907254fu", "967461", pic_id);
                    System.out.println(err_result);
                    return Result.error("枫斗~达达猫自动过验证码失败!");
                }
                if (verify_code.equals("1")){
                    System.out.println("枫斗自动过验证码成功!");
                    Notify.show("枫斗~达达猫自动过验证码成功!");
                    // 进行更新cookies
                    commo_Cookies = cookies;
                    Document rest_doc = Jsoup.parse(OkHttp.string(searchUrl, getHeader()));
                    List<Vod> list = parseVoc(rest_doc);
                    return Result.string(list);
                }
            }catch (JSONException e){
                Notify.show("枫斗~达达猫自动过验证码失败!");
                return Result.error("枫斗~达达猫自动过验证码失败!");
            }
        }
        List<Vod> list = parseVoc(doc);
        return Result.string(list);
    }

    /**
     * 达达龟过验证码逻辑->请求服务器获取cookies->请求验证图片cookies==发送验证码请求验证->验证码成功->cookies过验证码成功
     * @param code
     * @param cookies
     * @return
     */
    public String pass_verification_code(String code, String cookies){
        System.out.println("验证码");
        System.out.println(code);
        HashMap<String, String> headers = new HashMap<>();
        headers.put("user-agent",Util.CHROME);
        headers.put("x-requested-with", "XMLHttpRequest");
        headers.put("cookie", "PHPSESSID="+cookies);
        HashMap<String, String> params = new HashMap<>();
        params.put("type", "search");
        params.put("verify", code);
        OkResult post = OkHttp.post(verifyUrl, params, headers);
        if (post.getCode() == 200){
            return post.getBody();
        }
        System.out.println("请求失败:"+post.getCode());
        return "";
    }

    private List<Vod> parseVoc(Document doc) {
        Elements select = doc.select("div.stui-vodlist__box");
        List<Vod> list = new ArrayList<>();
        for (Element element : select) {
            String url = element.select(".stui-vodlist__thumb.lazyload").attr("href");
            String pic = element.select(".stui-vodlist__thumb.lazyload").attr("data-original");
            String name = element.select(".title > a").text();
            String remark = element.select("span.pic-text").text();
            list.add(new Vod(url, name, pic, remark));
        }
        return list;

    }
}
